//logs.js
const util = require('../../utils/util.js')
import * as utils from '../../utils/util.js'
import request from '../../utils/http.js'
import upload from '../../utils/upload.js'
import Toast from '@vant/weapp/toast/toast';
const app = getApp()
Page({
  data: {
    lock: true,
    title: '添加宝宝信息',
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else {
        return `${value}日`;
      }
    },
    changeArea: false,//地址选择框弹出
    familytiesisShow: false,//选择家庭关系弹出框
    birthdayshow: false,//宝宝生日选择框
    babyGendershow: false,//宝宝性别选择框
    carema: false,//照相机图标
    textColor: '#bfc7d3',
    areaList: {},//省市区列表
    familyList: [],//家庭关系
    genderList: [
      {
        name: '男',
        value: 0
      },
      {
        name: '女',
        value: 1
      }
    ],
    id: '',
    owner: '',
    userId:'',
    areaId: '',
    city: '',
    counties: '',
    province: '',
    userArea: "请选择接种地区",
    areaError: '',
    familys: "妈妈",
    relationIndex: 0,
    relationCode: 'mama',
    babyBirthday: "请选择宝宝生日",
    birthdayError: '',
    babyGender: "男",
    sex: '0',
    name: '',//宝宝昵称
    trueName: '',//宝宝姓名
    nameError: '',
    trueNameError: '',
    babyheadImg: '/images/child-portrait.png',
    areaids: [],//选中地址
    isChangeImg: false,
    editbtn:false,
    vxShow: true,
    baby:{},
    isLogin:false,
    vaccinePlanStatus: true,
  },
  onShow(){
    //检测用户是否登录
    let isLogin = wx.getStorageSync('isLogin') || app.globalData.isLogin;
    this.setData({
      isLogin: isLogin
    })
    this.errlogin(isLogin);
  },
  errlogin(isLogin){
    if (!isLogin) {
      wx.showModal({
        title: '系统提示',
        content: '您还未登录,是否去登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          } else if (res.cancel) {
            that.setData({
              isLogin: false
            })
          }
        }
      })
    }
  },
  changeArea() { //打开选择地址弹窗
    //选择地址弹窗处理
    this.setData({
      changeArea: true
    })
  },
  onClose() {//关闭选择地区弹窗
    this.setData({
      changeArea: false
    })
  },
  onLoad(options) {
    var baby = {}
    if (options.src) {//选完头像新增
      this.setData({
        title: '新增宝宝',
        babyheadImg: options.src
      })
    } else if (options.item) {//编辑
      baby = JSON.parse(decodeURIComponent(options.item));
      this.setData({
        title: '编辑宝宝信息',
        editbtn:true,
        vxShow: false,
        vaccinePlanStatus: baby.vaccinePlanStatus
      })
    }
    if (baby.sex != undefined ) {
      if (baby.sex == 1) {
        baby.babyGender = '女'
      } else {
        baby.babyGender = '男'
      }
      this.getbaby(baby)

    }

    let beforeEighteenyear = new Date(utils.reduceDate('Y', utils.formatDate(new Date()), "18")).getTime()
    this.getArea();//获取地址列表
    //获取家庭关系列表
    let dict = wx.getStorageSync("dict");
    let babyrelation = dict["BABYRELATION"];
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))
      }),
      familyList: babyrelation.data,
      minDate: beforeEighteenyear
    });
  },
  getbaby(baby){
    utils.HttpRequst(false, '/baby-cloud-base/mobileBabyRelation/detail', 'post', { babyId:baby.id }, (res) => {
      if (res.data.code == 200) {
        console.log(res.data.data)
        this.setData({
          familys: res.data.data.userCallName,
          relationCode: res.data.data.userCallCode
        })
      }
    })
    let birthday = baby.birthday.split(" ")[0]
    let date = new Date(birthday)
    this.setData({
      baby: baby,
      areaId: baby.areaId,
      name: baby.name,
      trueName: baby.trueName,
      city: baby.city,
      province: baby.province,
      counties: baby.counties,
      sex: baby.sex,
      babyGender: baby.babyGender,
      babyBirthday: birthday,
      userArea: baby.province + baby.city + baby.counties,
      babyheadImg: baby.headPath,
      id: baby.id,
      owner: baby.owner,
      currentDate: date.getTime(),
      userId: wx.getStorageSync('userInfo').userId
    })
  },

  complateSelArea(e) {
    let arealist = e.detail.values;
    let str = '';
    arealist.forEach((item) => {
      str = str + item.name;
    })
    this.setData({
      userArea: str,
      areaId: arealist[2].code,
      province: arealist[0].name,
      city: arealist[1].name,
      counties: arealist[2].name,
      areaError: ''
    })
    //处理完成关闭弹窗
    this.onClose();
  },
  cancel() {//选接种地区关闭
    //处理完成关闭弹窗
    this.onClose();
  },
  getArea() {//获取地区列表
    utils.HttpRequst(false, '/baby-cloud-base/area/selectAreaListByH5', 'post', {}, res => {
      if (res.data.code == 200) {
        this.setData({
          areaList: res.data.data
        })
      }
    })
  },
  changeFamily() {//选择家庭关系
    if(this.data.userId==this.data.owner){
      let list = this.data.familyList
      list.forEach((item, index) => {
        if (item.name == this.data.familys) {
          this.setData({
            relationIndex: index,
            familytiesisShow: true
          })
        }
      })
    }else{
      Toast('只有宝宝的创建者才能更改与宝宝关系')
    }
  },
  onCloseFamily() {//关闭选择家庭弹窗
    this.setData({
      familytiesisShow: false
    })
  },
  familyConfirm(e) {//选择家庭确认按钮
    console.log(e)
    this.setData({
      familys: e.detail.value.name,
      relationCode: e.detail.value.value,
      familytiesisShow: false
    })
  },
  familyCancel(e) {//选择家庭取消按钮
    this.setData({
      familytiesisShow: false
    })
  },
  babybirthday() {//宝宝生日弹窗
    this.setData({
      birthdayshow: true
    })
  },
  onClosebirthday() {//关闭宝宝生日弹窗
    this.setData({
      birthdayshow: false,
    })
  },
  birthdayComfirm(e) {
    let dateStr = utils.format(new Date(e.detail));
    this.setData({
      babyBirthday: dateStr,
      birthdayshow: false,
      birthdayError: ''
    })
  },
  birthdayCancel() {
    this.setData({
      birthdayshow: false
    })
  },
  babyGender() {//打开宝宝性别弹窗
    this.setData({
      babyGendershow: true
    })
  },
  babyGenClose() {//关闭宝宝性别弹窗
    this.setData({
      babyGendershow: false
    })
  },
  genderCancel() {//取消性别选择弹窗
    this.setData({
      babyGendershow: false
    })
  },
  genderConfirm(e) {//性别选择弹窗确认按钮
    console.log(e)
    this.setData({
      babyGender: e.detail.value.name,
      sex: e.detail.value.value,
      babyGendershow: false
    })
  },
  uploadBabyImg() {//选择宝宝头像
    let that = this;
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success(res) {
        let imgpath = res.tempFilePaths[0];
        wx.navigateTo({
          url: '/pages/cut-pictures/cut-pictures?src=' + imgpath,
        })
      },
      fail(err) {

      },
    })
  },
  nameInput(e) {
    let username = e.detail
    this.setData({
      name: username
    })
  },
  clearName() {
    this.setData({
      name: ""
    })
  },
  trueNameInput(e) {
    let truename = e.detail
    this.setData({
      trueName: truename
    })
  },
  clearTrueName() {
    this.setData({
      trueName: ""
    })
  },
  //校验宝贝昵称
  checkName(e) {
    let name = e.detail.value
    if (name.length < 2) {
      this.setData({
        nameError: "宝贝昵称由2-20个汉字、数字、英文组成"
      })
    } else if (!utils.checkBabyName(name)) {
      this.setData({
        nameError: "宝贝昵称由2-20个汉字、数字、英文组成"
      })
    } else {
      this.setData({
        nameError: ""
      })
    }
  },
  //校验宝贝姓名
  checkTrueName(e) {
    let trueName = e.detail.value
    if (trueName == '') {
      this.setData({
        trueNameError: ""
      })
    }else if (trueName.length < 2) {
      this.setData({
        trueNameError: "宝贝姓名由2-20个汉字，英文和全角点组成"
      })
    } else if (!utils.checkBabyTrueName(trueName)) {
      this.setData({
        trueNameError: "宝贝姓名由2-20个汉字，英文和全角点组成"
      })
    } else {
      this.setData({
        trueNameError: ""
      })
    }
  },
  //是否将宝宝月龄前疫苗标记为已接种
  changeVaccinePlan(e) {
      if(!e.detail) {
        this.setData({
          vaccinePlanStatus: false
        })
      }else {
        this.setData({
          vaccinePlanStatus: true
        })
      }
  },
  submit() {
    if(this.data.isLogin){
      if (!this.data.lock) {
        return
      }
      if (this.data.userArea == '请选择接种地区' || this.data.userArea == '' ) {
        this.setData({
          areaError: "请选择接种地区"
        })
        Toast(this.data.areaError)
        return;
      } else {
        this.setData({
          areaError: ""
        })
      }
      if (this.data.name == '') {
        this.setData({
          nameError: "请输入宝贝昵称"
        })
        Toast(this.data.nameError)
        return;
        }
      if (this.data.babyBirthday == '请选择宝宝生日') {
        this.setData({
          birthdayError: "请选择宝贝生日"
        })
        Toast(this.data.birthdayError)
        return;
      } else {
        this.setData({
          birthdayError: ""
        })
      }
      if (this.data.areaError == '' && this.data.nameError == '' && this.data.trueNameError == '' && this.data.birthdayError == '') {
      wx.showLoading()
      if (this.data.id == '') {//新增
        let data = {
          areaId: this.data.areaId,
          birthday: this.data.babyBirthday,
          city: this.data.city,
          counties: this.data.counties,
          headPath: this.data.babyheadImg,
          name: this.data.name,
          trueName: this.data.trueName,
          province: this.data.province,
          relationCode: this.data.relationCode,
          relationName: this.data.familys,
          sex: this.data.sex,
          vaccinePlanStatus: this.data.vaccinePlanStatus,
        }
        // //发送数据给服务器
        let tempFilePath = this.data.babyheadImg;
        if (tempFilePath === '/images/child-portrait.png'){
          data.headPath = 'https://hq-uat-ymxt.oss-cn-szfinance.aliyuncs.com/upload/store/pt/2020/01/1af30a5c-18f1-4bd6-a88a-102549375bfb.png'
          //没有添加头像
          utils.HttpRequst(false, '/baby-cloud-base/mobileBabyInfo/addItem', 'post', data, res => {
            if (res.data.code == 200) {//上传图片成功
              wx.hideLoading()
              //添加宝宝成功跳转至首页
              Toast('添加宝宝信息成功');
              let pages = getCurrentPages();
              let beforePage = pages[pages.length - 2];
              this.setData({
                lock: true
              })
              this.back()
            } else {
              wx.hideLoading()
              Toast(res.data.message);
              this.setData({
                lock: true
              })
            }
          })
        }else{//添加头像了，上传头像
          upload(tempFilePath, "pic_root").then(res => {
            if (res.status) {
              data.headPath = res.url;
              utils.HttpRequst(false, '/baby-cloud-base/mobileBabyInfo/addItem', 'post', data, res => {
                if (res.data.code == 200) {//上传图片成功
                  wx.hideLoading()
                  //添加宝宝成功跳转至首页
                  Toast('添加宝宝信息成功');
                  let pages = getCurrentPages();
                  let beforePage = pages[pages.length - 2];
                  this.setData({
                    lock: true
                  })
                  this.back()
                } else {
                  wx.hideLoading()
                  Toast(res.data.message);
                  this.setData({
                    lock: true
                  })
                }
              })
            } else {
              wx.hideLoading()
              Toast('添加宝宝失败请重新添加');
              return
            }

          })
        }

      } else {//编辑
        let data = {
          id: this.data.id,
          owner: this.data.owner,
          areaId: this.data.areaId,
          birthday: this.data.babyBirthday,
          city: this.data.city,
          counties: this.data.counties,
          headPath: this.data.babyheadImg,
          name: this.data.name,
          trueName: this.data.trueName,
          province: this.data.province,
          relationCode: this.data.relationCode,
          relationName: this.data.familys,
          sex: this.data.sex,
          vaccinePlanStatus: this.data.vaccinePlanStatus,
        }
        // //发送数据给服务器
          let tempFilePath = this.data.babyheadImg;
          upload(tempFilePath, "pic_root").then(res => {
            console.log(res)
            if (res.status == "true"){
              data.headPath = res.url;
            }
            utils.HttpRequst(false, '/baby-cloud-base/mobileBabyInfo/editItem', 'post', data, res => {
              wx.hideLoading()
              if (res.data.code == 200) {
                //添加宝宝成功跳转至首页
                Toast('修改宝宝信息成功');
                this.back()
              } else {
                Toast(res.data.message);
                this.getbaby(this.data.baby)
              }
            })
          }, err => {
            utils.HttpRequst(false, '/baby-cloud-base/mobileBabyInfo/editItem', 'post', data, res => {
              wx.hideLoading()
              if (res.data.code == 200) {
                //添加宝宝成功跳转至首页
                Toast('修改宝宝信息成功');
                this.back()
              } else {
                Toast(res.data.message);
                this.getbaby(this.data.baby)
              }
            })
          })
      }
    }

    }else{
      this.errlogin(that.data.isLogin)
    }
  },
  babydelete(){
    utils.HttpRequst(true,'/baby-cloud-base/mobileBabyInfo/delete','post',{
      id: this.data.id
    },res=>{
      console.log(res)
      if(res.data.code == 200){
        wx.navigateBack()
      }else{
        Toast(res.data.message);
      }
    })
  },
  back() {
    let pages = getCurrentPages();
    let beforePage = pages[pages.length - 2]; // -2 是上一个页面，-3是上上个页面以此类推。
    wx.navigateBack()
  },
})
